package com.huifaapp.mall.activity;


import android.app.FragmentTransaction;
import android.app.NotificationManager;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.SPUtils;
import com.google.gson.Gson;
import com.hjm.bottomtabbar.BottomTabBar;
import com.huifaapp.mall.R;
import com.huifaapp.mall.afinal.SPConstants;
import com.huifaapp.mall.api.ApiManager;
import com.huifaapp.mall.bean.Verston;
import com.huifaapp.mall.view.SelfDialog;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import java.util.ArrayList;

import cn.jpush.android.api.JPushInterface;

public class MainFragment extends AppCompatActivity{//implements View.OnClickListener, {
    FrameLayout frameLayout;
    public static final String KEY_TOKEN="TOKEN";
    /*
   * 保存MyTouchListener接口的列表
   */
    private ArrayList<MyTouchListener> myTouchListeners = new ArrayList<MyTouchListener>();
    /**
     * 定义首页、分类、积分兑换、购物车、我的tab的图标
     */
    public static RadioButton btnHomeID;//2
    public static RadioButton btnCustomize;//1
    public static RadioButton btnMineID;//4

    public static RadioButton btnfreetoenterID;//3
    /**
     * Notification管理
     */
    public NotificationManager mNotificationManager;
    public BottomTabBar bottomTabBar;
    /**
     * 定义首页、分类、购物车、我的Fragment
     */
//    CenterDialogVersion centerDialogVersion;
    public static HomeLivingMoneyFragement homeLivingMoneyFragment;//首页--生钱
    public static EarnMoneyFragment earnMoneyFragment;
    public static TribeFragment tribeFragment;
    public static MineFragment mineFragment;
    public  static FragmentTransaction ft;
    Verston list;
    TextView tv_shengjineirong;
    // 定义一个变量，来标识是否退出
    private static boolean isExit = false;

    Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
//        centerDialogVersion = new CenterDialogVersion(this, R.layout.dialog_layout_verston,
//                new int[]{R.id.iv_cancel_dialog_version,R.id.tv_shengjineirong, R.id.iv_mashangshengji});
//        centerDialogVersion.setOnCenterItemClickListener(this);
        setContentView(R.layout.main_view);

        LoadShareType();



        JPushInterface.setDebugMode(true);
        JPushInterface.init(this);
        JPushInterface.setAlias(MainFragment.this, SPUtils.getInstance().getString(SPConstants.KEY_USERID),null);
        //初始化要用到的系统服务
//        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//	        handler.sendEmptyMessage(0);
//        intiView();
//        initClick();
        bottomTabBar = (BottomTabBar) findViewById(R.id.bottom_tab_ba);
        bottomTabBar.init(getSupportFragmentManager())
                .setImgSize(80, 80)
                .setFontSize(11)
                .setTabPadding(4, 6, 10)
                .setChangeColor(Color.rgb(255, 59, 87), Color.rgb(105, 102, 102))
                .addTabItem("首页", R.drawable.shouye_d, R.drawable.shouye, HomeLivingMoneyFragement.class)
                .addTabItem("分类", R.drawable.fenlei_d, R.drawable.fenlei,Tmallclassify_Fragment.class)
                .addTabItem("店铺", R.drawable.dianpu_d, R.drawable.dianpu,Tmall_shopkeeperFragment.class)
                .addTabItem("我的", R.drawable.wode_d, R.drawable.wode,MineFragment.class)
                .isShowDivider(true);
    }

    /**
     * 获取版本号
     * @return 当前应用的版本号
     */
    public String getVersion() {
        try {
            PackageManager manager = this.getPackageManager();
            PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
            String version = info.versionName;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
    private void LoadShareType(){
        HttpUtils http = new HttpUtils();
        //http://www.jhjvip.cn:8081/market/mobile/jd/index?
        http.send(HttpRequest.HttpMethod.POST,  ApiManager.PROJECT_VERSION+"?type=android",new RequestCallBack<String>() {
            @Override
            public void onLoading(long total, long current, boolean isUploading) {
//                  testTextView.setText(current + "/" + total);
                Log.e("数据", "数据-------" + current + "/" + total);

            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
//                    textView.setText(responseInfo.result);
                Log.e("数据123", "数据dzhong-------" + responseInfo.result);
                Gson gson = new Gson();
                list = gson.fromJson(responseInfo.result, Verston.class);
                if(list.getCode().equals("10000")) {
                    if (getVersion().equals(list.getData().getVersion())) {

                    } else {

                        final SelfDialog selfDialog = new SelfDialog(MainFragment.this);
                        selfDialog.setMessage(list.getData().getDesc());
                        selfDialog.setiv(list.getData().getImage());
                        selfDialog.setYesOnclickListener(new SelfDialog.onYesOnclickListener() {
                            @Override
                            public void onYesClick() {
                                Uri uri = Uri.parse(list.getData().getDownload());
                                Intent it = new Intent(Intent.ACTION_VIEW, uri);
                                startActivity(it);
                                selfDialog.dismiss();
                            }
                        });
                        selfDialog.setNoOnclickListener(new SelfDialog.onNoOnclickListener() {
                            @Override
                            public void onNoClick() {
                                selfDialog.dismiss();
                            }
                        });
                        selfDialog.show();
                    }
                }
            }

//                        final AlertDialog.Builder builder = new AlertDialog.Builder(MainFragment.this);
//                        builder.setMessage("有新版本出现，要去升级吗？");
//                        builder.setTitle("版本");
//                        builder.setPositiveButton("去升级", new DialogInterface.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//                                Uri uri = Uri.parse(list.getData().getAppstoreDown());
//                                Intent it = new Intent(Intent.ACTION_VIEW, uri);
//                                startActivity(it);
//                                builder.create().dismiss();
//                            }
//                        });
//                        builder.setNegativeButton("不了", new DialogInterface.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//                                builder.create().dismiss();
//                            }
//                        });
//                        builder.create().show();




            @Override
            public void onStart() {
            }

            @Override
            public void onFailure(HttpException error, String msg) {
            }
        });
    }
//    @Override
//    public void OnCenterItemClick(CenterDialogVersion dialog, View view) {
//        Log.e("aaaaaaaaaaaaaaaaaa",list+"   "+list.getData().getVersionDesc()+"       "+list.getData().getAppstoreDown());
////         tv_shengjineirong = (TextView) dialog.findViewById(R.id.tv_shengjineirong);
////        tv_shengjineirong.setText(list.getData().getVersionDesc());
//            switch (view.getId()){
//
//                case R.id.iv_cancel_dialog_version:
//                    centerDialogVersion.dismiss();
//                    break;
//                case R.id.iv_mashangshengji:
//                    Uri uri = Uri.parse(list.getData().getAppstoreDown());
//                                Intent it = new Intent(Intent.ACTION_VIEW, uri);
//                                startActivity(it);
//                    centerDialogVersion.dismiss();
//                    break;
//            }
//    }
//    private void initClick() {
//        btnCustomize.setOnClickListener(this);
//        btnHomeID.setOnClickListener(this);
//        btnfreetoenterID.setOnClickListener(this);
//        btnMineID.setOnClickListener(this);
//    }

    private void intiView() {
//        btnCustomize = (RadioButton) findViewById(R.id.btnCustomize);
//        btnHomeID = (RadioButton) findViewById(R.id.btnHomeID);
//        btnfreetoenterID = (RadioButton) findViewById(R.id.btnfreetoenterID);
//        btnMineID= (RadioButton) findViewById(R.id.btnMineID);
//        frameLayout = (FrameLayout) findViewById(R.id.content);
////        btnCustomize.setBackgroundColor(Color.RED);
//        btnCustomize.setChecked(true);
//        initFragment1();
    }



    //    private void initFragment1() {
//
//        ft = getFragmentManager().beginTransaction();
//        homeLivingMoneyFragment = new HomeLivingMoneyFragement();
//        ft.add(R.id.content,homeLivingMoneyFragment);
//        ft.commit();
//    }
//
//    private void initFragment2() {
//        ft = getFragmentManager().beginTransaction();
//        earnMoneyFragment = new EarnMoneyFragment();
//        ft.add(R.id.content, earnMoneyFragment);
//        ft.commit();
//    }
//
//    private void initFragment3() {
//        ft = getFragmentManager().beginTransaction();
//        tribeFragment = new TribeFragment();
//        ft.add(R.id.content, tribeFragment);
//        ft.commit();
//    }
//
//    private void initFragment4() {
//        ft = getFragmentManager().beginTransaction();
//        mineFragment = new MineFragment();
//        ft.add(R.id.content, mineFragment);
//        ft.commit();
//    }
//
//
//    private void showFragment(Fragment fragment) {
//        FragmentTransaction ft = getFragmentManager().beginTransaction();
//        ft.show(fragment);
//        ft.commit();
//    }
//
//    private void hideFragment(Fragment fragment) {
//        FragmentTransaction ft = getFragmentManager().beginTransaction();
//        ft.hide(fragment);
//        ft.commit();
//    }
//
//    @Override
//    public void onClick(View view) {
//        switch (view.getId()) {
//            case R.id.btnCustomize:
//                show1();
//                break;
//            case R.id.btnHomeID:
//                show2();
//                break;
//            case R.id.btnfreetoenterID:
//                show3();
//                break;
//            case R.id.btnMineID:
//                show4();
//                break;
//        }
//    }
//
//    public  void show1() {
//        if (homeLivingMoneyFragment != null) {
//            showFragment(homeLivingMoneyFragment);
//        } else {
//            initFragment1();
//        }
//        if (earnMoneyFragment != null) {
//            hideFragment(earnMoneyFragment);
//        }
//        if (tribeFragment != null) {
//            hideFragment(tribeFragment);
//        }
//        if(mineFragment!=null){
//            hideFragment(mineFragment);
//        }
//
//        btnCustomize.setChecked(true);
//    }
//
//    public void show2() {
//        if (homeLivingMoneyFragment != null) {
//            hideFragment(homeLivingMoneyFragment);
//        }
//        if (earnMoneyFragment != null) {
//            showFragment(earnMoneyFragment);
//        } else {
//            initFragment2();
//        }
//        if (tribeFragment != null) {
//            hideFragment(tribeFragment);
//        }
//        if(mineFragment!=null){
//            hideFragment(mineFragment);
//        }
//
//        btnHomeID.setChecked(true);
//    }
//
//    public void show3() {
//        if (homeLivingMoneyFragment != null) {
//            hideFragment(homeLivingMoneyFragment);
//        }
//        if (earnMoneyFragment != null) {
//            hideFragment(earnMoneyFragment);
//        }
//        if (tribeFragment != null) {
//            showFragment(tribeFragment);
//        } else {
//            initFragment3();
//        }
//        if(mineFragment!=null){
//            hideFragment(mineFragment);
//        }
//
//        btnfreetoenterID.setChecked(true);
//    }
//    public void show4() {
//        if (homeLivingMoneyFragment != null) {
//            hideFragment(homeLivingMoneyFragment);
//        }
//        if (earnMoneyFragment != null) {
//            hideFragment(earnMoneyFragment);
//        }
//        if (tribeFragment != null) {
//            hideFragment(tribeFragment);
//        }
//        if(mineFragment!=null){
//            showFragment(mineFragment);
//        }else {
//            initFragment4();
//        }
//
//        btnMineID.setChecked(true);
//    }
    public interface MyTouchListener
    {
        public void onTouchEvent(MotionEvent event);
    }




    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        Log.v("shiran","--------33333333333-------------");

//        LogUtils.e("Info", "result:" + requestCode + " result:" + resultCode);
//        mAgentWeb.uploadFileResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }


    /**
     * 提供给Fragment通过getActivity()方法来注册自己的触摸事件的方法
     * @param listener
     */
    public void registerMyTouchListener(MyTouchListener listener)
    {
        myTouchListeners.add(listener);
    }
    /**
     * 提供给Fragment通过getActivity()方法来取消注册自己的触摸事件的方法
     * @param listener
     */
    public void unRegisterMyTouchListener(MyTouchListener listener)
    {
        myTouchListeners.remove(listener);
    }
    /**
     * 分发触摸事件给所有注册了MyTouchListener的接口
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        // TODO Auto-generated method stub
        for (MyTouchListener listener : myTouchListeners) {
            listener.onTouchEvent(ev);
        }
        return super.dispatchTouchEvent(ev);
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void exit() {
        if (!isExit) {
            isExit = true;
            Toast.makeText(getApplicationContext(), "再按一次退出程序",
                    Toast.LENGTH_SHORT).show();
            // 利用handler延迟发送更改状态信息
            mHandler.sendEmptyMessageDelayed(0, 2000);
        } else {
            finish();
            System.exit(0);
        }
    }
}
